<!--  -->
<template>
  <base-modal :title="title" :show.sync="visible" width="800px">
    <el-form
      :model="dispatchRuleForm"
      :rules="formRules"
      ref="ruleForm"
      label-position="top"
      
      class="dispatch-rule-form"
    >
      <!-- 名称 -->
      <el-form-item :label="`${$t('common.base.name')}：`" prop="displayName">
        <el-input
          v-model="dispatchRuleForm.displayName"
          :placeholder="$t('task.setting.taskSetting.placeholder8', {data: 20})"
          maxlength="20"
        ></el-input>
      </el-form-item>

      <!-- 规则类型 -->
      <el-form-item :label="`${$t('task.components.allotRuleModal.ruleType')}：`" prop="ruleType">
        <el-radio-group
          v-model="dispatchRuleForm.ruleType"
          @change="ruleChange"
        >
          <el-radio label="type">{{$t('event.setting.dispatchRuleDialog.byEventType')}}</el-radio>
          <el-radio label="select">{{$t('task.components.allotRuleModal.bySpecialCondition')}}</el-radio>
          <el-radio label="cusTag">{{$t('task.components.allotRuleModal.byCustomerTag')}}</el-radio>
          <el-radio label="service">{{$t('task.components.allotRuleModal.byServiceAddress')}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <div
        class="dispatch-rule-event-type"
        v-show="dispatchRuleForm.ruleType === 'type'"
      >
        <span>{{$t('event.setting.dispatchRuleDialog.eventTypeMeetConditions')}}：</span>
        <el-select
          v-model="dispatchRuleForm.type.typeInfo"
          :placeholder="$t('common.placeholder.select')"
          @change="getTypeMapList"
          filterable
          multiple
          remote
          clearable
          :remote-method="getTypeList"
          v-el-select-loadmore="loadmoreType"
        >
          <el-option
            v-for="item in eventTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>

      <div v-show="dispatchRuleForm.ruleType === 'select'">
        <div class="dispatch-rule-event-type">
          <span>{{$t('event.setting.dispatchRuleDialog.chooseEventType')}}：</span>
          <el-select
            v-model="dispatchRuleForm.select.typeInfo"
            :placeholder="$t('common.placeholder.select')"
            @change="getConditionDetail()"
            filterable
            remote
            clearable
            :remote-method="getTypeList"
            v-el-select-loadmore="loadmoreType"
          >
            <el-option
              v-for="item in eventTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div class="dispatch-rule-condition-detail">
          <span>{{$t('task.components.allotRuleModal.chooseApplicationConditions')}}</span>
          <el-select
            v-model="dispatchRuleForm.select.field"
            @change="fieldChange"
          >
            <el-option
              v-for="item in selectField"
              :key="item && item.id"
              :label="item && item.displayName"
              :value="item && item.fieldName"
            ></el-option>
          </el-select>
          <el-select v-model="dispatchRuleForm.select.operator">
            <el-option
              v-for="item in selectOperator"
              :key="item && item.value"
              :label="item && item.label"
              :value="item && item.value"
            ></el-option>
          </el-select>
          <el-select v-model="dispatchRuleForm.select.value">
            <el-option
              v-for="item in selectValue"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <!-- TODO 国际化待办 -->
          <span>{{$t('common.time.hour')}}</span>
        </div>
      </div>

      <div
        class="dispatch-rule-form-group"
        v-show="dispatchRuleForm.ruleType === 'cusTag'"
      >
        <span>{{$t('task.components.allotRuleModal.whenCustomerTeam')}}</span>
        <el-select
          v-model="dispatchRuleForm.cusTag.operator"
          class="dispatch-rule-group-select"
        >
          <el-option :label="$t('common.base.include')" value="包含"></el-option>
          <el-option :label="$t('common.base.exclude')" value="不包含"></el-option>
        </el-select>
        <span>{{$t('task.setting.taskSetting.text50')}}</span>
        <biz-team-select
          class="dispatch-rule-tag-select"
          :placeholder="$t('common.placeholder.inputSearch')"
          :value="dispatchRuleForm.cusTag.tagInfo"
          :fetch-func="fetchTagList"
          @input="handlerTeamChange"
          multiple
        />
      </div>

      <!-- 分配给指定人员下拉框 -->
      <el-form-item
        :label="`${$t('task.detail.components.assignTo')}：`"
        prop="serveOption"
        v-if="dispatchRuleForm.ruleType === 'service'"
      >
        <el-select v-model="dispatchRuleForm.serveOption">
          <el-option
            :label="$t('task.components.allotRuleModal.serviceAddressDepartment')"
            value="servicePositionTag"
          ></el-option>
          <el-option
            :label="$t('task.components.allotRuleModal.serviceAddressDepartmentManager')"
            value="servicePositionTagLeader"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="`${$t('task.detail.components.assignTo')}：`" prop="group" v-else>
        <el-select
          v-model="dispatchRuleForm.group"
          style="margin-bottom: 10px;"
          @change="groupChange"
        >
          <el-option :label="$t('common.base.userTypes.designatedUser')" value="user"></el-option>
          <el-option :label="$t('common.base.userTypes.designatedRole')" value="role"></el-option>
          <el-option :label="$t('common.base.userTypes.designatedService')" value="tag"></el-option>
          <el-option :label="$t('common.base.userTypes.designatedServiceManager')" value="tagLeader"></el-option>
          <el-option :label="$t('common.base.userTypes.designatedCustomerManager')" value="customerManager"></el-option>
          <el-option
            :label="$t('task.components.allotRuleModal.customerServiceDepartment')"
            value="cusTag"
            v-if="dispatchRuleForm.ruleType === 'cusTag'"
          ></el-option>
          <el-option
            :label="$t('task.components.allotRuleModal.customerServiceDepartmentManager')"
            value="cusTagLeader"
            v-if="dispatchRuleForm.ruleType === 'cusTag'"
          ></el-option>
        </el-select>

        <template v-if="dispatchRuleForm.group === 'user'">
          <biz-form-remote-select
            class="user-type-select"
            ref="TeamUserBizFormRemoteSelect"
            v-model="dispatchRuleForm.groupInfo.user"
            :placeholder="$t('common.placeholder.select')"
            :remote-method="fetchUsers"
            multiple
            @input="getUserMapList"
          >
            <div
              class="allot-users-option"
              slot="option"
              slot-scope="{ option }"
            >
              <contact-user-item
                :user="option"
                :show-user-state="true"
                :state-color="stateColor"
                :show-tag="true"
              />
            </div>
          </biz-form-remote-select>
        </template>
        <template v-else-if="dispatchRuleForm.group === 'role'">
          <el-select
            v-model="dispatchRuleForm.groupInfo.role"
            :placeholder="$t('common.placeholder.select')"
            filterable
            remote
            clearable
            :remote-method="getRoleList"
            v-el-select-loadmore="loadmoreRole"
            style="width: 100%;"
          >
            <el-option
              v-for="item in roleListReal"
              v-show="!item.notShow"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
        <template v-else-if="dispatchRuleForm.group === 'tag'">
          <biz-team-select
            class="dispatch-rule-tag-select"
            :placeholder="$t('common.placeholder.inputSearch')"
            :value="dispatchRuleForm.groupInfo.tag"
            :fetch-func="fetchTagList"
            @input="handlerTagChange"
          />
        </template>
        <template v-else-if="dispatchRuleForm.group === 'tagLeader'">
          <biz-team-select
            class="dispatch-rule-tag-select"
            :placeholder="$t('common.placeholder.inputSearch')"
            :value="dispatchRuleForm.groupInfo.tagLeader"
            :fetch-func="fetchTagList"
            @input="handlerTagLeaderChange"
          />
        </template>
      </el-form-item>

      <!-- 分配优先顺序 -->
      <el-form-item
        :label="$t('event.setting.dispatchRuleDialog.allotPriority')"
        prop="orderBy"
        v-if="dispatchRuleForm.group !== 'customerManager'"
      >
        <el-select v-model="dispatchRuleForm.orderBy" style="width: 100%">
          <el-option
            :label="$t('event.setting.dispatchRuleDialog.lessUnfinishedTaskPriorityAllot')"
            value="unfinishedTask"
          ></el-option>
          <el-option :label="$t('event.setting.dispatchRuleDialog.closerDistancePriorityAllot')" value="cusDistance"></el-option>
          <el-option :label="$t('task.components.allotRuleModal.distributeEvenlyInOrder')" value="polling"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" @click="confirm">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import * as SettingApi from "@src/api/SettingApi.ts";
import http from "@src/util/http";
import ContactUserItem from "@src/component/common/BaseContact/ContactUserItem.vue";
import _ from 'lodash';
import i18n from '@src/locales'

export default {
  data() {
    return {
      title: i18n.t('task.components.allotRuleModal.createAllotRule'),
      id: "",
      visible: false,
      mode: "",
      // todo 初始值结构
      typeInfo: [],
      dispatchRuleForm: {
        displayName: "",
        ruleType: "type",
        type: {
          typeInfo: [],
        },
        select: {
          typeInfo: "",
          field: "",
          operator: "",
          value: "",
        },
        cusTag: {
          operator: "包含",
          tagInfo: [],
        },
        group: "user",
        groupInfo: {
          user: [],
          role: "",
          roleName: "",
          tag: [],
          tagLeader: [],
        },
        serveOption: "servicePositionTag",
        orderBy: "unfinishedTask",
      },
      formRules: {
        displayName: [
          { required: true, message: i18n.t('common.placeholder.inputName'), trigger: "blur" },
          // {
          //   pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
          //   message: i18n.t('common.base.tip.inputLimit'),
          // },
        ],
        ruleType: [
          { required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.components.allotRuleModal.ruleType')}), trigger: "change" },
        ],
        group: [{ required: true, message: i18n.t('event.setting.dispatchRuleDialog.tip1'), trigger: "change" }],
        serveOption: [
          { required: true, message: i18n.t('event.setting.dispatchRuleDialog.tip1'), trigger: "change" },
        ],
        orderBy: [
          { required: true, message: i18n.t('event.setting.dispatchRuleDialog.tip2'), trigger: "change" },
        ],
      },
      typeParams: {
        keyword: "",
        pageNum: 1,
      },
      userParams: {
        keyword: "",
        pageNum: 1,
      },
      roleParams: {
        keyword: "",
        pageNum: 1,
      },
      loading: false,
      hasNextPage_type: true,
      hasNextPage_role: true,
      eventTypeList: [],
      roleList: [],
      selectUsers: [],
      // stateColor: {}, // 用户工作状态颜色
      selectField: [],
      selectFieldItem: {},
      selectOperator: [],
      selectValue: [],
      condition: {},
      typeMapList: [],
      tagMapList: [],
      userMapList: [],

      defaultRoleOption: void 0
    };
  },
  components: {
    ContactUserItem,
  },
  created() {
    this.initializeStateColor();
    this.getTypeList(true);
  },
  computed: {
    roleListReal() {
      let list = this.roleList || []
      if (this.defaultRoleOption && !list.find(v => v.id === this.defaultRoleOption.id)) {
        list = [
          this.defaultRoleOption,
          ...this.roleList
        ]
      }
      return list
    }
  },
  methods: {
    openDialog(mode, id = "") {
      if (mode === "create") {
        this.title = this.$t('task.components.allotRuleModal.createAllotRule');
        this.mode = "create";
        Object.assign(
          this.$data.dispatchRuleForm,
          this.$options.data().dispatchRuleForm
        );
      } else {
        this.title = this.$t('task.setting.taskSetting.text47');
        this.mode = "edit";
        this.id = id;
        Object.assign(
          this.$data.dispatchRuleForm,
          this.$options.data().dispatchRuleForm
        );
        this.getRuleRowData(id);
      }

      this.visible = true;
    },

    // 获得当前编辑行数据
    async getRuleRowData(id) {
      try {
        const params = { id };
        const result = await SettingApi.getRlueOne(params);
        if (result.status === 0) {
          this.showRowData(result.data);
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.error("get rule error", error);
      }
    },

    // 返显编辑行数据
    showRowData(data) {
      this.dispatchRuleForm.displayName = data.name;
      this.dispatchRuleForm.group = data.condition.group;
      this.dispatchRuleForm.orderBy = data.condition.orderBy;

      // TODO 国际化待办
      if (data.according === "事件类型") {
        this.dispatchRuleForm.ruleType = "type";
        this.typeMapList = data.condition.typeInfo;
        this.dispatchRuleForm.type.typeInfo = this.typeMapList.map(
          (item) => item.id
        );
      } else if (data.according === "选择项") {
        this.dispatchRuleForm.ruleType = "select";
        this.selectFieldItem.templateId = data.condition.templateId;
        this.selectFieldItem.templateName = data.condition.templateName;
        this.dispatchRuleForm.select.typeInfo = data.condition.templateId;
        const { operator, value } = data.condition
        this.getConditionDetail(operator, value);
        this.dispatchRuleForm.select.field = data.condition.fieldName;
        this.dispatchRuleForm.select.operator = data.condition.operator;
        this.dispatchRuleForm.select.value = data.condition.value;
      } else if (data.according === "客户团队") {
        this.dispatchRuleForm.ruleType = "cusTag";
        this.dispatchRuleForm.cusTag.operator = data.condition.operator;
        this.tagMapList = data.condition.tagInfo;
        this.dispatchRuleForm.cusTag.tagInfo = data.condition.tagInfo.map(
          (item) => {
            return { id: item.id, tagName: item.tagName || item.name };
          }
        );
      } else if (data.according === "服务位置") {
        this.dispatchRuleForm.ruleType = "service";
        this.dispatchRuleForm.group = "";
        this.dispatchRuleForm.serveOption = data.condition.group;
        return;
      }

      if (data.condition.group === "user") {
        this.userMapList = data.candidate.info;
        data.distributionUsers.forEach((item) => {
          item.label = item.displayName;
          item.value = item.userId;
        });
        this.dispatchRuleForm.groupInfo.user = data.distributionUsers;
      } else if (data.condition.group === "role") {
        let { groupId, groupName } = data.condition
        this.dispatchRuleForm.groupInfo.role = groupId;
        this.dispatchRuleForm.groupInfo.roleName = groupName;
        data.condition && (this.defaultRoleOption = {
          id: groupId,
          name: groupName,
          notShow: true
        })
        !this.roleList?.length && this.getRoleList(true)
      } else if (data.condition.group === "tag") {
        this.dispatchRuleForm.groupInfo.tag = [
          {
            id: data.condition.groupId,
            tagName: data.condition.groupName,
          },
        ];
      } else if (data.condition.group === "tagLeader") {
        this.dispatchRuleForm.groupInfo.tagLeader = [
          {
            id: data.condition.groupId,
            tagName: data.condition.groupName,
          },
        ];
      }
    },

    // 规则类型切换
    ruleChange() {
      if (this.dispatchRuleForm.ruleType !== "service") {
        this.getTypeList(true);
        this.dispatchRuleForm.group = "user";
      }
    },

    // 查询事件类型
    // todo 接口返回数据有问题
    async getTypeList(refresh = true) {
      try {
        this.loading = true;
        if (refresh) {
          this.typeParams.pageNum = 1;
        } else {
          this.typeParams.pageNum++;
        }
        const result = await SettingApi.getEventTypeList(this.typeParams);
        this.loading = false;
        this.hasNextPage_type = result.hasNextPage;
        if (refresh) {
          this.eventTypeList = result.list;
        } else {
          this.eventTypeList.push(...result.list);
        }
      } catch (error) {
        this.loading = false;
        console.error("get event type error", error);
      }
    },

    loadmoreType() {
      if (this.hasNextPage_type) this.getTypeList(false);
    },

    getTypeMapList(value) {
      this.typeMapList = [];
      value.map((item) => {
        const list = this.eventTypeList.find((list) => list.id === item);
        const obj = {
          id: list.id,
          name: list.name,
        };
        this.typeMapList.push(obj);
      });
    },

    async getConditionDetail(operator, value) {
      try {
        const params = {
          templateId: this.dispatchRuleForm.select.typeInfo,
          tableName: "event",
        };
        const result = await SettingApi.getEventTemplateFields(params);
        if (result) {
          this.selectField = result
            .filter((item) => item.formType === "select")
            .map((item) => {
              item.displayName += item.setting.isMulti ? `(${this.$t('common.base.multiple')})` : `(${this.$t('common.base.radio')})`;
              return item;
            });
          this.dispatchRuleForm.select.field = this.selectField[0]?.fieldName;
          this.fieldChange(this.selectField[0]?.fieldName, operator, value);
        }
      } catch (error) {
        console.error("get condition detail error", error);
      }
    },

    fieldChange(value, originOperator, originValue) {
      this.selectOperator = [];
      this.selectValue = [];
      this.selectFieldItem = {};

      this.selectField.forEach((item) => {
        if (item.fieldName === value) {
          if (item.setting.isMulti) {
            this.selectOperator = [
              { label: this.$t('common.base.include'), value: "包含" },
              { label: this.$t('common.base.exclude'), value: "不包含" },
            ];
          } else {
            this.selectOperator = [
              { label: this.$t('common.base.equal'), value: "等于" },
              { label: this.$t('common.base.notEqual'), value: "不等于" },
            ];
          }
          this.selectFieldItem = item;
          this.selectValue = item.setting.dataSource;
        }
      });

      this.dispatchRuleForm.select.operator = originOperator || this.selectOperator[0]?.value;
      this.dispatchRuleForm.select.value = originValue || this.selectValue[0];
    },

    // 查询部门标签
    async fetchTagList(params) {
      try {
        return await SettingApi.getTagList(params);
      } catch (error) {
        console.error("get tag list error", error);
      }
    },

    handlerTeamChange(value) {
      let tag = value;
      // this.dispatchRuleForm.cusTag.tagInfo = value;
      this.dispatchRuleForm.cusTag.tagInfo = tag.map((item) => {
        return { id: item.id, tagName: item.tagName };
      });
      this.tagMapList = tag.map((item) => {
        return { id: item.id, name: item.tagName };
      });
    },

    // 查询用户列表
    fetchUsers(params) {
      let { keyword, pageNum } = params;
      this.userParams = {
        pageNum,
        keyword,
      };

      return SettingApi.getAllotUsersList(this.userParams).then((res) => {
        if (!res || !res.list) return;

        res.list = res.list.map((item) =>
          Object.freeze({
            label: item?.displayName || "",
            value: item?.userId || "",
            ...item,
          })
        );

        return res;
      });
    },

    /** 初始化工作状态的颜色 */
    initializeStateColor() {
      http
        .get("/setting/getStateColorMap")
        .then(
          (res) => (this.stateColor = _.assign({}, this.stateColor, res || {}))
        )
        .catch((err) => console.error(err));
    },

    // 更改分配给类型
    groupChange() {
      if (this.dispatchRuleForm.group === "role") {
        this.getRoleList(true);
      }
    },

    // 查询角色列表
    async getRoleList(refresh = true) {
      try {
        this.loading = true;
        if (refresh) {
          this.roleParams.pageNum = 1;
        } else {
          this.roleParams.pageNum++;
        }
        const result = await SettingApi.getRoleList(this.roleParams);
        this.loading = false;
        this.hasNextPage_role = result.hasNextPage;
        if (refresh) {
          this.roleList = result.list;
        } else {
          this.roleList.push(...result.list);
        }
      } catch (error) {
        this.loading = false;
        console.error("get role list error", error);
      }
    },

    // 获取更多角色信息
    loadmoreRole() {
      if (this.hasNextPage_role) this.getRoleList(false);
    },

    handlerTagChange(value) {
      this.dispatchRuleForm.groupInfo.tag = value;
    },

    handlerTagLeaderChange(value) {
      this.dispatchRuleForm.groupInfo.tagLeader = value;
    },

    getUserMapList(value) {
      this.userMapList = value.map((item) => {
        return {
          userId: item.userId,
          userName: item.displayName,
          times: 0,
        };
      });
    },

    // 提交校验
    validator() {
      // 判断规则类型内容是否存在
      if (this.dispatchRuleForm.ruleType === "type") {
        if (this.dispatchRuleForm.type.typeInfo.length === 0) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('event.setting.dispatchRuleDialog.tip3'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.ruleType === "select") {
        if (!this.dispatchRuleForm.select.typeInfo) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('event.setting.dispatchRuleDialog.tip4'),
            type: "error",
          });
          return false;
        }
        if (
          !(
            this.dispatchRuleForm.select.field &&
            this.dispatchRuleForm.select.operator &&
            this.dispatchRuleForm.select.value
          )
        ) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('task.tip.allotRuleTip5'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.ruleType === "cusTag") {
        if (this.dispatchRuleForm.cusTag.tagInfo.length === 0) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('event.setting.dispatchRuleDialog.tip5'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.ruleType === "service") {
        return true;
      }

      // 判断分配给内容是否存在
      if (this.dispatchRuleForm.group === "user") {
        if (this.dispatchRuleForm.groupInfo.user.length === 0) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('task.setting.taskSetting.tip20'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.group === "role") {
        if (!this.dispatchRuleForm.groupInfo.role) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('event.setting.dispatchRuleDialog.tip6'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.group === "tag") {
        if (this.dispatchRuleForm.groupInfo.tag.length === 0) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('task.tip.allotRuleTip6'),
            type: "error",
          });
          return false;
        }
      } else if (this.dispatchRuleForm.group === "tagLeader") {
        if (this.dispatchRuleForm.groupInfo.tagLeader.length === 0) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: this.$t('task.tip.allotRuleTip7'),
            type: "error",
          });
          return false;
        }
      }

      return true;
    },

    // 新建规则提交
    bulidParmas() {
      const parmas = {
        module: "event",
        name: this.dispatchRuleForm.displayName,
        condition: {
          group: this.dispatchRuleForm.group,
          orderBy: this.dispatchRuleForm.orderBy,
        },
        candidate: {},
      };

      // 根据规则类型的不同，condition中传入不同的值
      // TODO 国际化待办
      if (this.dispatchRuleForm.ruleType == "type") {
        parmas.according = "事件类型";

        parmas.condition.typeInfo = this.typeMapList;
      } else if (this.dispatchRuleForm.ruleType == "select") {
        parmas.according = "选择项";

        parmas.condition.fieldName = this.dispatchRuleForm.select.field;
        parmas.condition.operator = this.dispatchRuleForm.select.operator;
        parmas.condition.value = this.dispatchRuleForm.select.value;

        parmas.condition.templateId = this.selectFieldItem.templateId;
        parmas.condition.templateName = this.selectFieldItem.templateName;
      } else if (this.dispatchRuleForm.ruleType == "cusTag") {
        parmas.according = "客户团队";

        parmas.condition.operator = this.dispatchRuleForm.cusTag.operator;
        parmas.condition.tagInfo = this.tagMapList;
      } else if (this.dispatchRuleForm.ruleType == "service") {
        parmas.according = "服务位置";

        parmas.condition.group = this.dispatchRuleForm.serveOption;
        return parmas;
      }

      // 根据分配类型的不同，candidate中传入不同的值
      if (this.dispatchRuleForm.group === "user") {
        parmas.candidate.info = this.userMapList;
      } else if (this.dispatchRuleForm.group === "role") {
        parmas.condition.groupId = this.dispatchRuleForm.groupInfo.role;
        const roleRow = this.roleList.find(
          (item) => item.id === this.dispatchRuleForm.groupInfo.role
        );
        parmas.condition.groupName =
          roleRow?.name || this.dispatchRuleForm.groupInfo.roleName;
      } else if (this.dispatchRuleForm.group === "tag") {
        parmas.condition.groupId = this.dispatchRuleForm.groupInfo.tag[0]?.id;
        parmas.condition.groupName = this.dispatchRuleForm.groupInfo.tag[0]?.tagName;
      } else if (this.dispatchRuleForm.group === "tagLeader") {
        parmas.condition.groupId = this.dispatchRuleForm.groupInfo.tagLeader[0]?.id;
        parmas.condition.groupName = this.dispatchRuleForm.groupInfo.tagLeader[0]?.tagName;
      }

      return parmas;
    },

    async createRule(parmas) {
      try {
        const result = await SettingApi.saveRlue(parmas);
        if (result.status === 0) {
          this.visible = false;
          this.$parent.getEventDispatchRules();
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.saveSuccess'),
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: `${this.$t('common.base.saveFail')}：` + result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.error("create rule error", error);
      }
    },

    async updateRule(parmas) {
      try {
        const result = await SettingApi.editRlue(parmas);
        if (result.status === 0) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.tip.edit2Success'),
            type: "success",
          });
          this.visible = false;
          this.$parent.getEventDispatchRules();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: "error",
          });
        }
      } catch (error) {
        console.error("update rule error", error);
      }
    },

    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid && this.validator()) {
          const parmas = this.bulidParmas();

          if (this.mode === "create") {
            this.createRule(parmas);
          } else {
            parmas.id = this.id;
            this.updateRule(parmas);
          }
        }
      });
    },
  },
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.dispatch-rule-form {
  margin: 20px 30px;

  .flexAndPadding {
    display: flex;
    align-items: center;
    padding-left: 20px;
    margin-bottom: 18px;
  }

  .dispatch-rule-event-type {
    @extend .flexAndPadding;

    span {
      width: 200px;
    }

    .el-select {
      width: calc(100% - 200px);
    }
  }

  .dispatch-rule-form-group {
    @extend .flexAndPadding;

    .dispatch-rule-group-select {
      width: 80px;
      margin: 0 10px;
    }

    .dispatch-rule-tag-select {
      width: 410px;
    }
  }

  .dispatch-rule-condition-detail {
    @extend .flexAndPadding;

    .el-select {
      margin: 0 10px;
    }

    .el-select + .el-select {
      margin-left: 0;
    }

    .el-select:nth-of-type(2) {
      width: 100px;
    }
  }
}

.select-popper {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-radio {
  margin: 0 20px 0 0;
}

.user-type-select ::v-deep .list-wrapper {
  width: 620px;
  left: auto;
  // height: 300px;
  // overflow: hidden;
}
</style>
